package com.fingard.dsp.bank.directbank.alipay01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

public class ALIPAY01BatPayRec extends ALIPAY01Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.reqSeqID = p_req1988.reqBatchNO;
        int i = 0;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1988.ownAct, "");
            if (actItem == null) {
                retAts.respCode = "0";
                retAts.respInfo = "未找到账号[" + p_req1988.readedDetail.payAct + "]商户配置信息";
                retAts.reqSeqID = p_req1988.readedDetail.askNumber;
                retAts.transState = PaymentState.FAIL_Payment;
                retAts.payInfoCode = FailCode.E9981;
                return retAts;
            }
            Map<String, String> params = new HashMap<String, String>();
            //接口名称
            params.put("service", "batch_trans_notify");
            //合作身份者ID
            params.put("partner", actItem.merchantId);
            //参数编码字符集
            params.put("_input_charset", "UTF-8");
            //服务器异步通知页面路径
            params.put("notify_url", actItem.notifyURL);
            //付款账号名
            params.put("account_name", p_req1988.ownActName);
            StringBuilder detail_data = new StringBuilder();
            while (p_req1988.readRecord()) {
                i ++;
                //流水号1^收款方账号1^收款账号姓名1^付款金额1^备注说明1|流水号2^收款方账号2^收款账号姓名2^付款金额2^备注说明2
                StringBuilder detail = new StringBuilder();
                if (StringHelper.hasAnyChar(p_req1988.readedDetail.askNumber)) {
                    detail.append(p_req1988.readedDetail.askNumber);
                }
                if (StringHelper.hasAnyChar(p_req1988.readedDetail.recAct)) {
                    detail.append("^").append(p_req1988.readedDetail.recAct);
                }
                if (StringHelper.hasAnyChar(p_req1988.readedDetail.recName)) {
                    detail.append("^").append(p_req1988.readedDetail.recName);
                }
                if (StringHelper.hasAnyChar(p_req1988.readedDetail.payAmount)) {
                    detail.append("^").append(p_req1988.readedDetail.payAmount);
                }
                if (StringHelper.hasAnyChar(p_req1988.readedDetail.memo)) {
                    detail.append("^").append(p_req1988.readedDetail.memo);
                }
                detail_data.append(detail).append("|");
            }
            String details = detail_data.replace(detail_data.length()-1, detail_data.length(), "").toString();
            //付款详细数据
            params.put("detail_data", details);
            //批量付款批次号
            params.put("batch_no", p_req1988.reqBatchNO);
            //付款总笔数
            params.put("batch_num", p_req1988.totalNum);
            //付款总金额
            params.put("batch_fee", p_req1988.totalAmt);
            //付款账号 付款方的支付宝账号，支持邮箱和手机号2种格式。
            params.put("email", p_req1988.ownAct);
            //支付日期
            params.put("pay_date", Format.Date8Format.format(Format.Date10Format.parse(p_req1988.payDate)));
            //付款账号别名
            params.put("buyer_account_name", "");
            //业务扩展参数
            params.put("extend_param", p_req1988.useType);

            String content = convertMapToStr(params);
            String sign = md5(content, actItem);

            //签名方式
            params.put("sign_type", actItem.signType);
            //签名
            params.put("sign", sign);

            String reqStr = convertMapToStr1(params);
            String[] tmpStrRet = sendToBank(reqStr, bankFront.getUrl("batPay"));

            if (tmpStrRet[0].length() == 0) {
                StringBuilder sbMsg = new StringBuilder();
                if (tmpStrRet[1].startsWith("<?xml")) {
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], sbMsg);
                    if (tmpBkReader != null) {
                        retAts.respCode = "0";
                        String isSuccess = tmpBkReader.getSimpleTextNotNull("is_success");
                        String responseCode = tmpBkReader.getFirstText("error");
                        if (StringHelper.hasAnyChar(responseCode)) {
                            retAts.transState = "is_success=" + isSuccess + "+" + responseCode;
                        } else {
                            retAts.transState = "is_success=" + isSuccess;
                        }
                        retAts.payInfoCode = responseCode;
                        retAts.respInfo = responseCode;
                    }
                } else {
                    retAts.respCode = "-6";
                    retAts.respInfo = tmpStrRet[1];
                }
            } else if (tmpStrRet[1] != null && tmpStrRet[1].length() > 0) {
                retAts.respCode = "-7";
                retAts.respInfo = tmpStrRet[1];
            } else {
                retAts.respCode = "-766";
                retAts.respInfo = "提交服务器异常";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.reqSeqID = p_req1998.reqBatchNO;

        FileReader reader = null;
        BufferedReader br = null;
        try {
            String tmpFileName = FGBiz.DSPHOME_Parent + File.separator + "signnotify";
            File tmpFile = new File(tmpFileName + File.separator + p_req1998.ownAct + ".txt");
            if (!tmpFile.exists()) {
                retAts.respCode = "0";
                retAts.respInfo = "转账未收到异步通知结果";
            } else {
                StringBuilder result = new StringBuilder();
                reader = new FileReader(tmpFile);
                br = new BufferedReader(reader);//构造一个BufferedReader类来读取文件
                String s = null;
                while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                    result.append(s);
                }
                WriteBankLogLn("异步通知结果：" + result);
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(result.toString(), tmpSbMsg);
                retAts.respCode = "0";
                while (tmpBkReader.read("/ATSYH/TransResp/TransParam/DetailRecord")) {
                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                    tmpRetDetail.payAct = tmpBkReader.readedXElement.getSingleText("PayAct");
                    tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("RecAct");
                    tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("RecName");
                    tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("PayAmount");
                    tmpRetDetail.result = tmpBkReader.readedXElement.getSingleText("Result");
                    tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("PostScript");//加入一个编号来确认这条记录信息
                    tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("Memo");
                    tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("PayInfoCode");
                    retAts.writeRetDetail(tmpRetDetail);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (br != null) {
                br.close();
            }
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}
